package services

import (
	"jianianhua-server/database"
	"jianianhua-server/models"
)

// RoleService 角色管理服务
type RoleService struct{}

// NewRoleService 创建角色服务实例
func NewRoleService() *RoleService {
	return &RoleService{}
}

// IsAdmin 检查用户是否为管理员
func (s *RoleService) IsAdmin(userID uint) (bool, error) {
	var user models.User
	err := database.DB.Select("role").Where("id = ?", userID).First(&user).Error
	if err != nil {
		return false, err
	}
	return user.Role == "admin", nil
}

// SetUserRole 设置用户角色
func (s *RoleService) SetUserRole(userID uint, role string) error {
	return database.DB.Model(&models.User{}).Where("id = ?", userID).Update("role", role).Error
}

// GetUserRole 获取用户角色
func (s *RoleService) GetUserRole(userID uint) (string, error) {
	var user models.User
	err := database.DB.Select("role").Where("id = ?", userID).First(&user).Error
	if err != nil {
		return "", err
	}
	return user.Role, nil
}

// GetAdminUsers 获取所有管理员用户
func (s *RoleService) GetAdminUsers() ([]models.User, error) {
	var users []models.User
	err := database.DB.Where("role = ?", "admin").Find(&users).Error
	return users, err
}

// PromoteToAdmin 将用户提升为管理员
func (s *RoleService) PromoteToAdmin(userID uint) error {
	return s.SetUserRole(userID, "admin")
}

// DemoteToUser 将管理员降级为普通用户
func (s *RoleService) DemoteToUser(userID uint) error {
	return s.SetUserRole(userID, "user")
}
